import React, { useEffect, useState } from 'react';
import { message, Modal, Tabs } from 'antd';
import { ConnectState } from '@/models/connect';
import { connect, Dispatch } from 'umi';
import { ITableListItem } from '../../type';
import Jurisdiction from './JurisdictionRight';

const { TabPane } = Tabs;

export interface FormValueType extends Partial<ITableListItem> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}

export interface RightsManagementProps {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  visible: boolean;
  userId: number;
  dispatch: Dispatch;
  projectList: any;
  parentType: string;
  userRoleLoading: boolean;
  userRole: any[];
}

const RightsManagementForm: React.FC<RightsManagementProps> = (props) => {
  const {
    dispatch,
    projectList, // 项目权限列表
    onCancel: handleModalVisible, // 关闭弹框
    visible, // 是否显示弹框
    userId, // 操作的用户对象ID
    userRoleLoading,
  } = props;
  const [type, setType] = useState<string>('4'); // 目前弹框卡片类型
  const [submitRoleKeys, setSubmitRoleKeys] = useState<Array<any>>([]); // 需要提交保存的分配角色ID
  const [submitProjectList] = useState<Array<any>>([]); // 需要提交保存的项目权限ID
  const [dataRoleBinds, setDataRoleBinds] = useState<Array<any>>([]); // 需要提交保存的数据权限

  const selectJurisdiction = (keys: Array<any>, tree: Array<any>) => {
    const bindsArr: any[] = [];

    for (let i = 0; i < keys.length; i++) {

      const data = tree.filter(v => v.key === keys[i])[0];

      if (!data) {
        return;
      }
      // 判断为全选
      if (keys[i].indexOf('-') === -1) {
        bindsArr.push({
          dataroleId: data.data.dataroleId,
          values: ['.*'],
        });
      } else if (bindsArr.filter(v => v.dataroleId === data.data.dataroleId).length === 0) {
        const idArr: Array<string> = [];
        data.data.values.forEach((v: any) => {
          idArr.push(v.id);
        });
        bindsArr.push({
          dataroleId: data.data.dataroleId,
          values: idArr,
        });
      } else {
        bindsArr.map((item: any) => {
          if (item.dataroleId === data.data.dataroleId) {
            const idArr: Array<string> = [];
            data.data.values.forEach((v: any) => {
              idArr.push(v.id);
            });
            item.values = [item.values, ...idArr];
          }
          return item;
        });
      }
    }
    setDataRoleBinds(bindsArr);

  };
  // 保存编辑结果
  const preservation = () => {
    if (type === '1') {
      // 分配角色
      if (submitRoleKeys.length === 0) {
        message.warning('请选择需要分配的角色');
        return;
      }
      dispatch({
        type: 'userManage/submitRole',
        payload: { roleIds: submitRoleKeys, userId },
        callback: (response: any) => {
          const { header } = response;
          if (header.code === 200) {
            message.success('分配成功');
          } else {
            message.warning('分配失败');
          }
          handleModalVisible();
        },
      });
      return;
    }

    if (type === '3') {
      // 项目权限
      if (submitProjectList.length === 0) {
        message.warning('请选择需要分配权限的项目');
        return;
      }
      dispatch({
        type: 'userManage/submitProject',
        payload: { departmentNos: submitProjectList, dashboardId: userId },
        callback: (response: any) => {
          const { header } = response;
          if (header.code === 200) {
            message.success('权限设置成功');
          } else {
            message.warning('权限设置失败');
          }
          handleModalVisible();
        },
      });
    }

    if (type === '4') {
      dispatch({
        type: 'dataRole/saveRoleDataBind',
        payload: { dataRoleBinds, userId },
        callback: (response: any) => {
          const { header } = response;
          if (header.code === 200) {
            message.success('分配成功');
          } else {
            message.warning('分配失败');
          }
          handleModalVisible();
        },
      });
    }
  };

  // 获取需要提交保存的分配角色ID
  // const getSubmitRoleKeys = (value: Array<any>) => {
  //   // 过滤去除添加的父级ID前缀
  //   const childKeys = value.map((key: string) => {
  //     const selectId = key.split('-')[1];
  //     return Number(selectId);
  //   });
  //   setSubmitRoleKeys(childKeys);
  // };

  useEffect(() => {
    // 获取项目权限列表
    if (projectList.length === 0) {
      dispatch({
        type: 'userManage/fetchProject',
      });
    }
    dispatch({
      type: 'dataRole/fetchUserRole',
      payload: { id: userId },
    });
    dispatch({
      type: 'dataRole/fetchRoleAllList',
    });
  }, []);
  return (
    <Modal
      width={1000}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title='权限管理'
      visible={visible}
      onOk={preservation}
      onCancel={() => handleModalVisible()}
    >
      <Tabs
        type='card'
        onChange={(key: string) => {
          setType(key);
        }}
      >
        {/* TODO 用户权限管理 */}
        {/* <TabPane tab="分配角色" key="1"> */}
        {/*  <RoleRight getSubmitRoleKeys={getSubmitRoleKeys} /> */}
        {/* </TabPane> */}
        {/* <TabPane tab="看板权限" key="2">
          <Widget/>
        </TabPane>
        {parentType === 'User' && (
          <TabPane tab="项目权限" key="3">
            <Checkbox.Group
              options={projectList.map((v: IProject) => {
                return { label: v.name, value: v.id.toString() };
              })}
              defaultValue={[]}
              onChange={setProjectList}
            />
          </TabPane>
        )} */}
        <TabPane tab='分配行权限' key='4'>
          {!userRoleLoading ? <Jurisdiction selectJurisdiction={selectJurisdiction} userId={userId} /> : null}

        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default connect(({ userManage, dataRole }: ConnectState) => ({
  projectList: userManage.projectList || [],
  userRoleLoading: dataRole.userRoleLoading,
  userRole: dataRole.userRole || [],

}))(RightsManagementForm);
